home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 13794 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  75 lines

  1. Path: news.ichange.com!newsmaster
  2. From: Jesse Liberty <jl@staff.ichange.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: NEWBIE : Quicksort
  5. Date: Wed, 27 Mar 1996 07:24:26 -0500
  6. Organization: AT&T
  7. Message-ID: <3159337A.2DB5@staff.ichange.com>
  8. References: <Pine.SOL.3.91.960324135520.8433A-100000@orion> <4j4ruf$gf4@news1.h1.usa.pipeline.com> <Pine.SOL.3.91.960325221334.202B-100000@orion>
  9. NNTP-Posting-Host: 140.244.99.60
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (Win95; I)
  14. CC: jl@staff.ichange.com
  15.  
  16. FRANCO wrote:
  17. > On 25 Mar 1996, Pete Grant wrote:
  18. > >    int n = sizeof(z) / sizeof(int);
  19. > >    qsort(z, n, sizeof(int), comp);
  20. > >    for (int i = 0; i < n; i++)
  21. > >       cout << ' ' << z[i];
  22. > Pete,
  23. > Can this be done without using qsort from the standard library <stdlib.h>?
  24.  
  25. Sure, in my book Teach Yourself MORE C++ In 21 Days I show how to write a number of sorts, quicksort among them. Here's the 
  26. basic code. 
  27.  
  28.     template <class T>
  29.     void myQuickSort(T* Input, int left, int right)
  30.     {
  31.        if (right > left)
  32.        {
  33.           T target = Input[right-1];
  34.           int i = left-1;
  35.           int x = right-1;
  36.           for (;;)
  37.           {
  38.              while (*Input[++i] < *target)
  39.              ;
  40.              while (*Input[--x] > *target)
  41.              ;
  42.  
  43.              if (i >= x)
  44.                 break;
  45.              Swap(Input[i], Input[x]);
  46.           }
  47.  
  48.           Swap(Input[i], Input[right-1]);
  49.           myQuickSort(Input,left,i);
  50.           myQuickSort(Input,i+1,right);
  51.  
  52.        }
  53.     }
  54.  
  55.     template <class T>
  56.     inline void Swap(T& i, T& j)
  57.     {
  58.        T temp;
  59.        temp = j;
  60.        j = i;
  61.        i = temp;
  62.     }
  63.  
  64. ------
  65. Jesse Liberty [AT&T New Media Services]
  66. jl@staff.ichange.com    ZDNet: 72241,72
  67. Teach Yourself C++ In 21 Days. Sams 1994
  68. Teach Yourself MORE C++ In 21 Days. Sams 1996
  69. Teach Yourself ANSI C++ In 21 Days. Sams 1996
  70. C++: An Introduction To Programming. Que 1996
  71.